const Op = require('sequelize').Op
const config = require('./../../config')
const models = require('../../db/mysqldb/index')
const { lowdb } = require('../../db/lowdb/index')
const { createAdminSystemLog } = require('./adminSystemLog')
const logger = require('./../../utils/logger')
const { SuccessModel, ErrorModel, validate, encrypt } = require('./../../utils/index')
const { checkUserName, checkPwd, checkEmail } = require('./../../utils/validators')
const jwt = require('jsonwebtoken')
const svgCaptcha = require('svg-captcha')
class AdminUser {
  /**
   * 测试
   * @param {*} req 
   */
  static async helloworld (req, res) {
    res.end('helloworld ')
  }

  static async getCode (req, res) {
    const codeConfig = {
      size: 2,
      ignoreChars: '0o1i',
      noise: 1,
      color: true,
      // 宽度
      width: 130,
      // 高度
      height: 40,
      background: "#cc9966"
    }
    let captcha = svgCaptcha.createMathExpr(codeConfig)
    req.session.captcha = captcha.text.toLocaleLowerCase()
    res.json(new SuccessModel({ data: captcha.data }))
  }

  /**
   * 用户登录
   * @param {String} account 
   * @param {String} password 
   * @param {String} captcha 
   */
  static async adminSignIn (req, res) {
    let { account, password, captcha } = req.body
    console.log(req.body);
    logger.info('AdminUser', 'adminSignIn', 'req.body', req.body)
    if (!account) {
      res.json(new ErrorModel([], `请输入账号`))
      return
    }
    if (!password) {
      res.json(new ErrorModel([], `请输入密码`))
      return
    }
    if (!captcha) {
      res.json(new ErrorModel([], `请输入验证码`))
      return
    }
    try {
      const sessionCaptcha = req.session.captcha
      if (sessionCaptcha !== captcha) {
        res.json(new ErrorModel([], `验证码错误`))
        return
      }
      const oneAdminUser = await models.admin_user.findOne({
        where: { account }
      })
      logger.info('AdminUser', 'adminSignIn', 'oneAdminUser', oneAdminUser)
      if (oneAdminUser) {
        const validate_flag = await validate(password, oneAdminUser.password)
        logger.info('AdminUser', 'adminSignIn', 'validate_flag', validate_flag)
        if (validate_flag) {
          res.json(new ErrorModel([], `密码错误`))
        }
        if (!oneAdminUser.enable) {
          res.json(new ErrorModel([], `您已被限制登录!`))
        }
        let datas = {
          uid: oneAdminUser.uid,
          account,
          role_id: oneAdminUser ? oneAdminUser.admin_role_ids : '',
          type: 'admin'
        }
        jwt.sign(
          datas,
          config.secretOrKey,
          // 设置过期时间
          { expiresIn: 60 * 60 * 24 },
          (err, token) => {
            if (err) {
              logger.info('AdminUser', 'adminSignIn', 'jwt-err', err)
              res.json(new ErrorModel([], err.message))
            } else {
              logger.info('AdminUser', 'adminSignIn', 'jwt-token', token)
              res.json(new SuccessModel({ token: 'Bearer ' + token, isLogin: true }, '登录成功'))
            }
          }
        )
      } else {
        res.json(new ErrorModel([], `用户不存在`))
      }
    } catch (error) {
      logger.info('AdminUser', 'adminSignIn', 'error', error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * 注册操作
   * @param {string} account 
   * @param {string} nickname 
   * @param {string} password 
   * @param {string} email 
   * @param {string} phone 
   * @param {string} enable 
   */
  static async createAdminUser (req, res) {
    logger.info('AdminUser', 'createAdminUser', 'req.body', req.body)
    const { account, nickname, password, email } = req.body
    try {
      if (!account) {
        res.json(new ErrorModel([], '请输入账户!'))
      }
      if (!nickname) {
        res.json(new ErrorModel([], '请输入昵称!'))
      }
      if (!checkUserName(account)) {
        res.json(new ErrorModel([], '账户须5-22个英文字符!'))
      }
      if (!password) {
        res.json(new ErrorModel([], '请输入密码!'))
      }
      if (!checkPwd(password)) {
        res.json(new ErrorModel([], '密码格式输入有误!'))
      }
      if (!checkEmail(email)) {
        res.json(new ErrorModel([], '邮箱格式输入有误!'))
      }
      let admin_user_res = await models.admin_user.findOne({
        where: {
          account
        }
      })
      logger.info('AdminUser', 'createAdminUser', 'admin_user_res', admin_user_res)
      if (admin_user_res) {
        res.json(new ErrorModel([], '账户已存在!'))
      }
      const password_encrypt = await encrypt(password, config.saltTime)
      const admin_user_create = await models.admin_user.create({
        account,
        avatar: config.default_avatar,
        nickname,
        password: password_encrypt,
        email,
        phone,
        enable: enable || false
      })
      logger.info('AdminUser', 'createAdminUser', 'admin_user_create', admin_user_create)
      res.json(new SuccessModel([], '注册成功'))
    } catch (error) {
      logger.info('AdminUser', 'createAdminUser', 'error.message', error.message)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * 更新管理员用户
   * @param {string} uid 
   * @param {string} account 
   * @param {string} nickname 
   * @param {string} password 
   * @param {string} email 
   * @param {string} phone 
   * @param {string} enable 
   */

  static async editAdminUser (req, res) {
    const { uid, account, nickname, password, email, phone, enable } = req.body
    logger.info('AdminUser', 'editAdminUser', 'req.body', req.body)
    try {
      if (!uid) {
        res.json(new ErrorModel([], '缺少参数!'))
      }
      let admin_user_res = await models.admin_user.findById(uid)
      logger.info('AdminUser', 'editAdminUser', 'admin_user_res', admin_user_res)
      if (admin_user_res) {
        const password_encrypt = await encrypt(password, config.saltTime)
        logger.info('AdminUser', 'editAdminUser', 'password_encrypt', password_encrypt)
        const admin_user_upd = await models.admin_user.update({
          account,
          nickname,
          password: password_encrypt,
          email,
          phone,
          enable: enable || false
        }, {
          where: {
            uid
          }
        })
        logger.info('AdminUser', 'editAdminUser', 'admin_user_upd', admin_user_upd)
        res.json(new SuccessModel([], '更新成功!'))
      } else {
        res.json(new ErrorModel([], 'uid有误!'))
      }
    } catch (error) {
      logger.info('AdminUser', 'editAdminUser', 'error.message', error.message)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * 后台用户列表
   * @param {*} page 
   * @param {*} limit 
   */
  static async getAdminUserList (req, res) {
    const { page = 1, limit = 10 } = req.query
    logger.info('AdminUser', 'getAdminUserList', 'req.query', req.query)
    logger.info('AdminUser', 'getAdminUserList', 'req.user', req.user)
    try {
      let { count, rows } = await models.admin_user.findAndCountAll({
        attributes: [
          'uid',
          'account',
          'nickname',
          'email',
          'phone',
          'last_sign_time',
          'enable',
          'admin_role_ids'
        ],
        where: '', // 为空，获取全部，也可以自己添加条件
        offset: (Number(page) - 1) * Number(limit), // 开始的数据索引，比如当page=2 时offset=10 ，而pagesize我们定义为10，则现在为索引为10，也就是从第11条开始返回数据条目
        limit: Number(limit) // 每页限制返回的数据条数
      })
      logger.info('AdminUser', 'getAdminUserList', 'count', count)
      logger.info('AdminUser', 'getAdminUserList', 'rows', rows)
      res.json(new SuccessModel({ count, rows, page, limit }, 'success!'))
    } catch (error) {
      logger.info('AdminUser', 'getAdminUserList', 'error.message', error.message)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * 获取后台用户信息
   * jwt 用户信息
   */
  static async getAdminUserInfo (req, res) {
    const { user = {} } = req
    logger.info('AdminUser', 'getAdminUserInfo', 'user', user)
    try {
      const { role_id } = user
      const website = lowdb.read().get('website').value()
      logger.info('AdminUser', 'getAdminUserInfo', 'website', website)
      let oneAdminRole = await models.admin_role.findOne({
        where: {
          role_id
        }
      })
      logger.info('AdminUser', 'getAdminUserInfo', 'oneAdminRole', oneAdminRole)
      let whereParmas = { authority_type: '1' }

      role_id !== config.SUPER_ROLE_ID && (whereParmas['authority_id'] = {
        [Op.in]: oneAdminRole.admin_authority_ids.split(',')
      })
      logger.info('AdminUser', 'getAdminUserInfo', 'whereParmas', whereParmas)
      let AllAuthorityName = await models.admin_authority.findAll({
        where: whereParmas
      })
      logger.info('AdminUser', 'getAdminUserInfo', 'AllAuthorityName', AllAuthorityName)

      let allAuthorityNameId = []
      for (const index in AllAuthorityName) {
        if (AllAuthorityName.hasOwnProperty(index)) {
          allAuthorityNameId.push(AllAuthorityName[index].authority_url)
        }
      }
      logger.info('AdminUser', 'getAdminUserInfo', 'allAuthorityNameId', allAuthorityNameId)

      let oneAdminUser = await models.admin_user.findOne({
        attributes: [
          'uid',
          'avatar',
          'account',
          'nickname',
          'email',
          'phone',
          'last_sign_time',
          'enable'
        ]
      })
      logger.info('AdminUser', 'getAdminUserInfo', 'allAuthorityNameId', allAuthorityNameId)
      res.json(new SuccessModel({ admin_user_info: oneAdminUser, all_authority_name_id: allAuthorityNameId, website }, 'success'))
    } catch (error) {
      logger.info('AdminUser', 'getAdminUserInfo', 'error.message', error.message)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * 删除用户信息
   * jwt 用户信息
   */
  static async deleteAdminUser (req, res) {
    const { uid } = req.body
    logger.info('AdminUser', 'deleteAdminUser', 'req.body', req.body)
    try {
      const admin_user_destory = await models.admin_user.destroy({
        where: { uid }
      })
      logger.info('AdminUser', 'deleteAdminUser', 'admin_user_destory', admin_user_destory)
      const system_log = await createAdminSystemLog({
        uid: req.user.uid,
        type: 3,
        content: `成功删了了id为‘${uid}’的管理员`
      })
      logger.info('AdminUser', 'deleteAdminUser', 'system_log', system_log)
      res.json(new SuccessModel([], `删除管理员用户成功`))
    } catch (error) {
      logger.info('AdminUser', 'deleteAdminUser', 'error.message', error.message)
      res.json(new ErrorModel([], error.message))
    }
  }
}
module.exports = {
  AdminUser
}